package com.falcon.service.impl;

import com.falcon.config.GeneratorConfig;
import com.falcon.enums.GeneratorTypeEnum;
import com.falcon.mapper.ITableMapper;
import com.falcon.service.IJavaGeneratorService;
import com.falcon.generator.java.IJavaGenerator;
import com.falcon.domain.po.TablePO;
import com.falcon.domain.req.GenerateRequest;
import com.falcon.utils.PathUtil;
import com.swan.core.constants.NumberConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zongf
 * @since 2023-05-26
 **/
@Slf4j
@Service
public class JavaGeneratorService implements IJavaGeneratorService {

    @Autowired
    private List<IJavaGenerator> codeGeneratorList;

    @Autowired
    private ITableMapper genTableMapper;

    @Autowired
    private GeneratorConfig generatorConfig;

    @Override
    public void generateJava(GenerateRequest request) {
        List<IJavaGenerator> matchGenerators = this.getMatchGenerators(request);

        TablePO tablePO = this.genTableMapper.selectById(request.getId());



        // 更新生成记录
        tablePO.setStatus(NumberConstant.ZERO);
        tablePO.setAuthor(request.getAuthor());

        String classSimpleName = PathUtil.handleClassName(tablePO.getTableName(), generatorConfig.getTablePrefix());
        tablePO.setClassName(classSimpleName);

        this.genTableMapper.updateNotNull(tablePO);


        for (IJavaGenerator matchGenerator : matchGenerators) {
            matchGenerator.generateCode(request.getId());
        }

    }

    public List<IJavaGenerator> getMatchGenerators(GenerateRequest request) {

        List<GeneratorTypeEnum> codeTypeEnums = new ArrayList<>();
        if (request.isHasPo())  codeTypeEnums.add(GeneratorTypeEnum.Java_PO);
        if (request.isHasMapper())  codeTypeEnums.add(GeneratorTypeEnum.Java_Mapper);
        if (request.isHasMapperXml())  codeTypeEnums.add(GeneratorTypeEnum.Java_Mapper_Xml);
        if (request.isHasDo())  codeTypeEnums.add(GeneratorTypeEnum.Java_DO);
        if (request.isHasServiceApi())  codeTypeEnums.add(GeneratorTypeEnum.Java_Service_Api);
        if (request.isHasService())  codeTypeEnums.add(GeneratorTypeEnum.Java_Service);
        if (request.isHasRequest())  codeTypeEnums.add(GeneratorTypeEnum.Java_Request);
        if (request.isHasQuery())  codeTypeEnums.add(GeneratorTypeEnum.Java_Query);
        if (request.isHasController())  codeTypeEnums.add(GeneratorTypeEnum.Java_Controller);

        List<IJavaGenerator> generatorList = this.codeGeneratorList.stream()
                .filter(generator -> codeTypeEnums.contains(generator.codeType()))
                .collect(Collectors.toList());

        return generatorList;
    }



}
